package com.asiainfo.hybridapp.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.asiainfo.hybridapp.R;
import com.asiainfo.hybridapp.configs.ConstantsME;
import com.asiainfo.hybridapp.entity.PopulationRankInfo;
import com.framework.utils.CollectionUtil;
import com.framework2.baseEvent.BaseOnClickListener;
import com.framework2.customLoading.LoadingFooter;
import com.framework2.customLoading.indicators.BallSpinFadeLoaderIndicator;
import com.framework2.utils.CustomProgressDialogUtils;
import com.library.adapter_recyclerview.UniversalAdapter;
import com.library.pulltorefresh.BaseAbstractPullToRefreshLayout;
import com.library.pulltorefresh.classical.SoftClassicalPullToRefreshLayout;
import com.library.pulltorefresh.pullableview.PullableRecyclerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class ListFragment extends Fragment implements PullableRecyclerView.OnAutoLoadListener {
    private Context mContext;
    private View view;// infalte的布局
    private LinearLayout containerLayout;// 新建容器
    ////////////////////////////////
    private SoftClassicalPullToRefreshLayout refreshLayout;
    private PullableRecyclerView recyclerView;
    private UniversalAdapter adapter;
    private List<PopulationRankInfo> infoList = new ArrayList<>();
    private LoadingFooter footerView;
    private boolean requestSuccess;
    private int page = 1;
    private int pageSize = 30;
    ////////////////////////////////
    private SimpleDateFormat simpleDateFormat;

    private PopulationRankInfo newMessageInfo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        Bundle arguments = getArguments();
        if (null != arguments && null != arguments.getSerializable(ConstantsME.entity)) {
            newMessageInfo = (PopulationRankInfo) arguments.getSerializable(ConstantsME.entity);
        }
    }

    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        if (null == view) {
            containerLayout = new LinearLayout(mContext);
            view = inflater.inflate(R.layout.fragment_message, null);
            view.setMinimumHeight(((WindowManager) getActivity()
                    .getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getHeight());
            view.setMinimumWidth(((WindowManager) getActivity()
                    .getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getWidth());
            containerLayout.addView(view);
        } else {
            containerLayout.removeAllViews();
            containerLayout = new LinearLayout(getActivity());
            containerLayout.addView(view);
        }
        initView();
        initRecyclerView();
        if (!requestSuccess) {
            CustomProgressDialogUtils.showProcessDialog(mContext, "店铺消息");
            requestShopMessageList();
        }
        return containerLayout;
    }

    private void initView() {
        recyclerView = (PullableRecyclerView) view.findViewById(R.id.recyclerView);
        refreshLayout = (SoftClassicalPullToRefreshLayout) view.findViewById(R.id.refresh_view);
    }

    private View initFooter() {
        footerView = new LoadingFooter(mContext);
        footerView.setLoadingHint("加载更多");
        footerView.setNoMoreHint("到底了");
        footerView.setNoNetWorkHint("网络不给力啊，点击再试一次吧");
        footerView.setState(LoadingFooter.State.Loading);
        footerView.setProgressStyle(BallSpinFadeLoaderIndicator.class);
        return footerView;
    }

    @SuppressWarnings("unchecked")
    private void initRecyclerView() {
        recyclerView.setHasFixedSize(true);
        recyclerView.setCanPullDown(true);
        recyclerView.setCanPullUp(false);
        recyclerView.setHasMoreData(false);
        recyclerView.setOnAutoLoadListener(this);
        refreshLayout.setRefreshContentTextView("店铺消息");
        refreshLayout.setLoadContentTextView("店铺消息");
        refreshLayout.setEmptyTxt("店铺消息为空,点击刷新");
        refreshLayout.setOnRefreshListener(new BaseAbstractPullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(final BaseAbstractPullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件刷新完毕了哦！
                        // pullToRefreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
                        CustomProgressDialogUtils.showProcessDialog(mContext, "店铺消息");
                        requestShopMessageList();
                    }
                }.sendEmptyMessageDelayed(0, 100);
            }

            @Override
            public void onLoadMore(final BaseAbstractPullToRefreshLayout pullToRefreshLayout) {
                // 加载操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件加载完毕了哦！
                        // pullToRefreshLayout.loadmoreFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 100);
            }
        });
        //第一种，简单的颜色，高度,水平分割线
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        if (CollectionUtil.getInstance().isEmpty(infoList)) {
            refreshLayout.showEmptyView();
        }
        adapter = initAdapter(adapter);
        recyclerView.setAdapter(adapter);
    }

    /**
     * @param adapter adapter
     * @return UniversalAdapter
     */
    @SuppressWarnings("unchecked")
    private UniversalAdapter initAdapter(UniversalAdapter adapter) {
        if (adapter == null) {
            adapter = new UniversalAdapter<PopulationRankInfo>(getActivity(), R.layout.listitem_shopmessage, infoList) {
                @Override
                protected void getItemView(UniversalViewHolder viewHolder, PopulationRankInfo info, int position) {
                    if (null == simpleDateFormat) {
                        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                    }
//                    RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams
//                    .MATCH_PARENT, (int)((ScreenUtils.getInstance().getScreenHeightPx(mContext)- ScreenUtils
//                    .getInstance().getStatusBarHeightPx(mContext)- ScreenUtils.getInstance().dip2px(mContext,50))*0
//                    .11));
//                    viewHolder.itemView.setLayoutParams(params);
//                    viewHolder.setImageResource(R.id.icon_remark, info.getIsReaded() ? R.drawable
//                    .shape_circle_gray_10dp : R.drawable.shape_circle_blue);
//                    viewHolder.setText(R.id.tv_title, info.getTitle());
//                    viewHolder.setText(R.id.tv_content, info.getContent());
//                    try {
//                        String date = simpleDateFormat.format(new Date(Long.parseLong(info.getDate())*1000));
//                        info.setDate(date);
//                    } catch (NumberFormatException e) {
//                        e.printStackTrace();
//                    }
//                    viewHolder.setText(R.id.tv_time, info.getDate());

//                    viewHolder.getView(R.id.btnReaded).setTag(R.id.shopMessageReadedTag, info);//已读
//                    viewHolder.getView(R.id.btnReaded).setTag(R.id.shopMessageReadedViewHolderTag, viewHolder);
//                    viewHolder.getView(R.id.btnReaded).setTag(R.id.shopMessageReadedPositionTag, position);
//                    viewHolder.getView(R.id.btnReaded).setOnClickListener(onReadedClickListener);
//
//                    viewHolder.getView(R.id.btnDelete).setTag(R.id.shopMessageDeleteTag, info);//删除
//                    viewHolder.getView(R.id.btnDelete).setTag(R.id.shopMessageDeletePositionTag, position);
//                    viewHolder.getView(R.id.btnDelete).setOnClickListener(onDeleteClickListener);
//
//                    viewHolder.getView(R.id.rootView).setTag(R.id.shopMessageReadedViewHolderTag, viewHolder);
//                    viewHolder.getView(R.id.rootView).setTag(R.id.shopMessageReadedPositionTag, position);
//                    viewHolder.getView(R.id.rootView).setTag(R.id.shopMessageTag, info);//item点击 //已读
//                    viewHolder.getView(R.id.rootView).setOnClickListener(onItemClickListener);
                }
            };
        }
        return adapter;
    }

    private BaseOnClickListener onDeleteClickListener = new BaseOnClickListener() {
        @Override
        public void onBaseClick(View v) {
//            PopulationRankInfo info = (PopulationRankInfo) v.getTag(R.id.shopMessageDeleteTag);
//            if (null != info) {
//                if (null != v.getTag(R.id.shopMessageDeletePositionTag)) {
//                    int position = (int) v.getTag(R.id.shopMessageDeletePositionTag);
//                    List list = GreenDaoManager.getInstance().queryEntityList(mContext, MessageInfo.class);
//                    if (!CollectionUtil.getInstance().isEmpty(list)) {
//                        for (int i = 0; i < list.size(); i++) {
//                            MessageInfo infoTemp = (MessageInfo) list.get(i);
//                            if (TextUtils.equals(info.getId(), infoTemp.getId()) && !infoTemp.getIsDeleted()) {
//                                infoTemp.setIsDeleted(true);
//                                GreenDaoManager.getInstance().updateEntity(mContext, infoTemp);
//                            }
//                        }
//                    }
//                    adapter.deleteData(position);
            CustomProgressDialogUtils.showProcessDialog(mContext, "删除消息");
//                    requestDeleteOneMessage(info.getId(), position);
//                }
//            }
        }
    };

    private BaseOnClickListener onReadedClickListener = new BaseOnClickListener() {
        @Override
        public void onBaseClick(View v) {
//            final PopulationRankInfo info = (PopulationRankInfo) v.getTag(R.id.shopMessageReadedTag);
//            if (null != info) {
//                if (null != v.getTag(R.id.shopMessageReadedPositionTag)) {
//                    final int position = (int) v.getTag(R.id.shopMessageReadedPositionTag);
//                    CustomProgressDialogUtils.showProcessDialog(mContext, "标记已读");
//                    if (null != v.getTag(R.id.shopMessageReadedViewHolderTag)) {
//                        UniversalAdapter.UniversalViewHolder viewHolder = (UniversalAdapter.UniversalViewHolder) v
//                        .getTag(R.id.shopMessageReadedViewHolderTag);
//                        if (null != viewHolder) {
////                            requestRemarkOneMessage(info, viewHolder, position);
//                        }
//                    }
//                }
//            }
        }
    };

    private void requestShopMessageList() {
//        HttpUtil.getInstance().requestShopMessageList((BaseActivity) mContext, InterfaceConfig.shopMessageList,
//        page, pageSize, new HttpUtil.OnRequestListResult<MessageInfo>() {
//            @Override
//            public void onSuccess(List<PopulationRankInfo> list, String... msg) {
//                saveLastMessageIntoDB(list);
//                requestSuccess = true;
//                refreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
//                recyclerView.setOnLoading(false);
//                CustomProgressDialogUtils.dismissProcessDialog();
//                if (!CollectionUtil.getInstance().isEmpty(list)) {
//                    if (page == 1) {
//                        dealNewMessage(list);
//                        infoList.clear();
//                    }
//                    infoList.addAll(list);
//                    adapter.notifyDataSetChanged();
//                } else if (CollectionUtil.getInstance().isEmpty(infoList)) {
//                    page = 1;
//                    refreshLayout.showEmptyView();
//                }
//                try {
//                    String totalCount = msg[0];
//                    int totalCount_ = Integer.parseInt(totalCount);
//                    recyclerView.setHasMoreData(page * pageSize < totalCount_);
//                    if (page * pageSize >= totalCount_) {
//                        if (footerView != null) {
//                            footerView.setState(LoadingFooter.State.NoMore);
//                        }
//                    } else {
//                        if (adapter.getFooterCount() <= 0) {
//                            adapter.addFooterViewAfterSetAdapter(initFooter());
//                        }
//                        page++;
//                    }
//                } catch (Exception e) {
//                    recyclerView.setHasMoreData(false);
//                    if (footerView != null) {
//                        footerView.setState(LoadingFooter.State.NoMore);
//                    }
//                }
//            }
//
//            @Override
//            public void onFail(int code, String msg) {
//                refreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.FAIL);
//                recyclerView.setOnLoading(false);
//                CustomProgressDialogUtils.dismissProcessDialog();
//                ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "获取店铺消息失败" : msg);
//            }
//        });
    }

    @Override
    public void onAutoLoad(final PullableRecyclerView pullableRecyclerView) {
        pullableRecyclerView.setOnLoading(true);
        new Handler() {
            @Override
            public void handleMessage(Message msg) {
                requestShopMessageList();
            }
        }.sendEmptyMessageDelayed(0, 100);
    }
}
